package com.jinunn.file.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.jinunn.file.service.FileService;
import com.jinunn.file.utils.ConstantOssUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author JinDun
 * @date 2021/5/18 22:04
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantOssUtils.EDNPOINT;
        String accessKeyId = ConstantOssUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssUtils.SECRECT;
        String bucketName = ConstantOssUtils.BUCKET;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = null;
        try {
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            inputStream = file.getInputStream();

            String fileName = System.currentTimeMillis()+file.getOriginalFilename();

            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, fileName, inputStream);

            //放回url格式：https://jinunn-mall.oss-cn-chengdu.aliyuncs.com/2021-01-02/1111.jpg
            return "https://"+bucketName+"."+endpoint+"/"+fileName;
        } catch (IOException e) {
            log.debug(e.getMessage(),e);
            e.printStackTrace();
            return null;
        }finally {
            if (inputStream!=null){
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }
}
